/**
 * 公共函数
 * @event {Function} getNowDate 获取当前时间 年-月-日
 * @event { Function } getDay 获取当前周几
 * @event { Function } getBottomHight 获取底部安全区
 * @event { Function } showToast 显示消息提示框
 * @event { Function } setImgage 图片地址拼接
 * @event { Function } formatRichText 处理富文本图片
 * @event { Function } checkPhone 判断手机号
 */

import env from '@/utils/env.js'
import { selectimes } from "@/api/home.js"
export const getNowDate = () => {
	const timeOne = new Date();
	const year = timeOne.getFullYear();
	let month = timeOne.getMonth() + 1;
	let day = timeOne.getDate();
	month = month < 10 ? '0' + month : month;
	day = day < 10 ? '0' + day : day;
	const nowMonths = `${year}-${month}-${day}`;
	return nowMonths;
}

export const getTmdhms = (timestamp) => {
	// 确保时间戳是数字
	if (typeof timestamp !== 'number') {
		timestamp = Number(timestamp);
	}
	// 检查时间戳是否是有效的数字
	if (isNaN(timestamp)) {
		return 'Invalid timestamp';
	}
	// 确保时间戳是以毫秒为单位的，如果是以秒为单位则乘以1000
	if (timestamp.toString().length === 10) {
		timestamp *= 1000;
	}
	let time = new Date(timestamp);
	let year = time.getFullYear();
	const month = (time.getMonth() + 1).toString().padStart(2, '0');
	const date = time.getDate().toString().padStart(2, '0');
	const hours = time.getHours().toString().padStart(2, '0');
	const minute = time.getMinutes().toString().padStart(2, '0');
	const second = time.getSeconds().toString().padStart(2, '0');
	return `${year}-${month}-${date} ${hours}:${minute}:${second}`;
}

export const getDay = (time) => {
	const week = new Date(time).getDay()
	const weeks = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]
	return weeks[week]
}

export const getBottomHight = () => {
	const app = uni.getSystemInfoSync();
	const bottomHight = app.safeAreaInsets.bottom
	return bottomHight
}

export const showToast = (title) => {
	uni.showToast({
		title: title,
		icon: 'none',
	})
}

export const checkPhone = (str) => {
	let re = /^[0-9]{11}$/
	if (re.test(str)) {
		return true
	} else {
		return false
	}
}

export const setImgage = (url) => {
	return "https://xhf.vipyingying.com" + url
}
export const setState = (state) => {
	let str = ''
	if (state === 1) str = '待支付';
	else if (state === 2) str = '待预约';
	else if (state === 3) str = '待核销';
	else if (state === 4) str = '退款中';
	else if (state === 5) str = '退款完成';
	else if (state === 6) str = '服务已完成';
	else if (state === 7) str = '已关闭';
	else if (state === 8) str = '待接单';
	else if (state === 9) str = '已评价';
	else if (state === 10) str = '接单超时';
	else if (state === 11) str = '订单待确定';
	return str
}

export const formatRichText = (str) => {
	let newContent = str.replace(/<img[^>]*>/gi, function (match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		return match;
	});
	newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
		return match;
	});
	newContent = newContent.replace(/<br[^>]*\/>/gi, '');
	newContent = newContent.replace(/\<img/gi, '<img style="width:100%;height:auto;display:inline-block;"');
	return newContent;
}

export const timeFormat = (dateTime, formatStr = 'yyyy-mm-dd') => {
	let date

	// 若传入时间为假值，则取当前时间
	if (!dateTime) {
		date = new Date()
	}
	// 若为unix秒时间戳，则转为毫秒时间戳（逻辑有点奇怪，但不敢改，以保证历史兼容）
	else if (/^\d{10}$/.test(dateTime?.toString().trim())) {
		date = new Date(Number(dateTime) * 1000)
	}

	// 若用户传入字符串格式时间戳，new Date无法解析，需做兼容
	else if (typeof dateTime === 'string' && /^\d+$/.test(dateTime.trim())) {
		date = new Date(Number(dateTime))
	}

	// 处理平台性差异，在Safari/Webkit中，new Date仅支持/作为分割符的字符串时间
	// 处理 '2022-07-10 01:02:03'，跳过 '2022-07-10T01:02:03'
	else if (typeof dateTime === 'string' && dateTime.includes('-') && !dateTime.includes('T')) {
		date = new Date(dateTime.replace(/-/g, '/'))
	}
	// 其他都认为符合 RFC 2822 规范
	else {
		date = new Date(dateTime)
	}

	const timeSource = {
		'y': date.getFullYear().toString(), // 年
		'm': (date.getMonth() + 1).toString().padStart(2, '0'), // 月
		'd': date.getDate().toString().padStart(2, '0'), // 日
		'h': date.getHours().toString().padStart(2, '0'), // 时
		'M': date.getMinutes().toString().padStart(2, '0'), // 分
		's': date.getSeconds().toString().padStart(2, '0') // 秒
		// 有其他格式化字符需求可以继续添加，必须转化成字符串
	}

	for (const key in timeSource) {
		const [ret] = new RegExp(`${key}+`).exec(formatStr) || []
		if (ret) {
			// 年可能只需展示两位
			const beginIndex = key === 'y' && ret.length === 2 ? 2 : 0
			const source = timeSource[key].toString()
			formatStr = formatStr.replace(ret, source.slice(beginIndex))
		}
	}
	return formatStr
}

export const getTimeThirty = (days, timesa, plus, createTime) => {
  let weeks = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  const createDate = new Date(createTime);  // 假设 createTime 是有效的日期字符串
  // 定义时间段范围
  const startDate = new Date("2024-12-15");
  const endDate = new Date("2025-02-05");
  // 最大日期为 2024-12-01，判断 createDate 是否大于等于该日期
  const maxCreateDate = new Date("2024-12-01 00:00:00");
  return new Array(Number(days)).fill(0).map((_, index) => {
    const date = new Date(new Date().getTime() + ((index + Number(timesa) + Number(plus)) * (24 * 60 * 60 * 1000)));
    const time = date.getFullYear() + '-' + (date.getMonth() + 1) + "-" + date.getDate();
    const day = date.getDay();
    // 判断 isMake 的条件
    let isMake = 1; //
    if (createDate <= maxCreateDate && date >= startDate && date <= endDate) {
      isMake = 0; // 可预约
    }
    return {
      id: index,
      time: time,
      day: weeks[day],
      isMake: isMake
    };
  });
};


export default (Vue) => {
	Vue.prototype['$getNowDate'] = getNowDate
	Vue.prototype['$getDay'] = getDay
	Vue.prototype['$getBottomHight'] = getBottomHight
	Vue.prototype['$showToast'] = showToast
	Vue.prototype['$setImgage'] = setImgage
	Vue.prototype['$formatRichText'] = formatRichText
	Vue.prototype['$checkPhone'] = checkPhone
	Vue.prototype['$getTmdhms'] = getTmdhms
	Vue.prototype['$setState'] = setState
}
